package com.monitor.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.monitor.entity.pojo.accesstoken.AccessToken;
import com.monitor.entity.pojo.sediment.SedimentLicense;
import com.monitor.module.accesstoken.service.AccessTokenService;
import com.monitor.module.accesstoken.service.impl.AuthServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * 车牌识别.
 *
 * @author Li Zhiyuan
 * @since 2020-11-20
 */
@Component
public class LicensePlate {
    @Autowired
    private AccessTokenService tokenService;

    @Autowired
    private AuthServiceImpl authService;

    // 请求百度接口地址url
//    private final String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate";


    @Value("${sediment.url}")
    private String url;
 /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */

    public SedimentLicense licensePlate(MultipartFile frontPhoto) {

        try {
            // 本地文件路径
//            String filePath = "D:/桌面/2345截图20201119151532.png";
//            byte[] imgData = FileUtil.readFileByBytes(filePath);
            byte[] imgData = FileUtil.readFileByBytes(frontPhoto);

            String imgStr = Base64Utils.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            //当前时间减去15天
            Date date = Date.from(Instant.now().minus(Duration.ofDays(15)));
//            AccessTokenService tokenService = new AccessTokenServiceImpl();
            List<AccessToken> list = tokenService.list(Wrappers.<AccessToken>lambdaQuery());
            StringBuilder accessToken = new StringBuilder();
            if (list.size() != 0 && date.before(list.get(0).getCreateTime())) {
                accessToken.append(list.get(0).getAccessToken());
            } else if (list.size() == 0) {
                AccessToken pojo = new AccessToken();
                accessToken.append(authService.getAuth());
                pojo.setAccessToken(accessToken.toString());
                pojo.setCreateTime(new Date());
                tokenService.save(pojo);
            } else {
                AccessToken pojo = new AccessToken();
                accessToken.append(authService.getAuth());
                pojo.setAccessToken(accessToken.toString());
                pojo.setCreateTime(new Date());
                tokenService.update(pojo, Wrappers.<AccessToken>lambdaQuery().eq(AccessToken::getId, list.get(0).getId()));
            }

//            String accessToken = "24.46c627caafa8d9ba21189bf827aa8655.2592000.1608368368.282335-23010742";

            String result = HttpUtil.post(url, accessToken.toString(), param);
            System.out.println(result);
            return GsonUtils.fromJson(result, SedimentLicense.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
